<template>
  <view class="home-container">
    <scroll-view scroll-y class="scroll-view">
      <view class="content-area">
        <map style="height: 500rpx; width: 100%" :latitude="latitude" :longitude="longitude" :markers="markers"
          :polyline="polyline" :controls="mapControls" show-location @regionchange="onRegionChange" @controltap="onControlTap" />
        <view class="notice-bar-container">
          <uv-notice-bar :text="notice"></uv-notice-bar>
        </view>
        <view class="phone-container">
          <view @click="callPhone"
            style="display: flex;align-items: center;gap: 10rpx;background-color: #f8f8f8;padding: 10rpx;border-radius: 10rpx;">
            <uv-icon name="phone-fill" :color="'#FF6B35'" :size="20"></uv-icon>
            <view class="notice-text">客服电话</view>
          </view>
        </view>
      </view>

      <view class="card-wrap">
        <uv-cell-group :border="false" customStyle="background-color: #fff; border-radius: 16rpx;">
          <uv-cell :border="false" is-link clickable @click="chooseAddress">
            <template #icon>
              <uv-icon name="map" color="#FF6B35" />
            </template>
            <template #title>
              <view class="addr-title-box">
                <text class="addr-title">{{ currentAddress }}</text>
                <text class="addr-detail">{{ currentDistrict }}</text>
              </view>
            </template>
          </uv-cell>
        </uv-cell-group>
      </view>

      <view class="card-wrap">
        <uv-cell-group :border="false" customStyle="background-color: #fff; border-radius: 16rpx;">
          <uv-cell :title="infoTitle.supplier">
            <template #value>
              <uv-tags text="柴油供应商" size="mini" type="success"></uv-tags>
            </template>
          </uv-cell>
          <uv-cell :title="infoTitle.carrier" :border="false">
            <template #value>
              <uv-tags text="柴油运输商" size="mini" type="warning"></uv-tags>
            </template>
          </uv-cell>
        </uv-cell-group>
      </view>

      <view class="card-wrap">
        <uv-cell-group :border="false" customStyle="background-color: #fff; border-radius: 16rpx;">
          <uv-cell is-link icon="integral-fill" title="选择油品" @click="chooseOilProduct">
            <template #value>
              {{ oilProduct }}
            </template>
          </uv-cell>
          <uv-cell icon="integral-fill">
            <template #title>
              <uv-input placeholder="请输入用油量" :border="'none'" v-model="oilQuantity">
                <template v-slot:suffix>升 </template>
              </uv-input>
            </template>
          </uv-cell>
          <uv-cell icon="integral-fill" :title="oilTime || '请选择用油时间'" @click="chooseOilTime">
            <template #right-icon>
              <uv-icon name="calendar" color="#999" :size="20" />
            </template>
          </uv-cell>
          <uv-cell icon="integral-fill" title="联系方式">
            <template #value>
              <uv-input placeholder="请输入联系方式" :border="'none'" v-model="oilPhone">
              </uv-input>
            </template>
          </uv-cell>
        </uv-cell-group>
      </view>
      <view class="card-wrap" @click="submitOrder">
        <button class="submit-btn-custom">提交订单</button>
      </view>
    </scroll-view>
    <uv-datetime-picker ref="datetimePicker" v-model="nowTime" mode="datetime" :minDate="new Date()" @confirm="confirm1">
    </uv-datetime-picker>

    <!-- 选择油品弹窗（底部弹出） -->
    <uv-popup ref="oilProductPopup" mode="bottom" :round="16" :closeable="true" :overlay="true" :safeAreaInsetBottom="true" :zIndex="10000" @close="closeOilProductPopup">
      <view class="oil-product-popup">
        <view class="popup-header">
          <text class="popup-title">选择油品</text>
        </view>
        <scroll-view class="popup-content" scroll-y :lower-threshold="60" @scrolltolower="loadMore">
          <view v-for="(item, index) in oilProductList" :key="index" class="oil-product-item">
            <view class="oil-type-badge">
             <image :src="item.goods_image" mode="widthFix" style="width: 100%;height: 100%;"></image>
            </view>
            <view class="product-info">
              <text class="product-name">{{ item.goods_name }}</text>
              <view class="price-info">
                <text class="currency">¥</text>
                <text class="price">{{ item.goods_menoy }}</text>
                <text class="unit">元/L</text>
              </view>
            </view>
            <uv-button text="立即下单" size="small" color="#FF6B35" customStyle="border-radius: 20rpx; min-width: 120rpx;"
              @click="orderOilProduct(item)" />
          </view>
          <view class="list-footer">
            <text v-if="loadingMore">加载中...</text>
            <text v-else-if="noMore">没有更多了</text>
          </view>
        </scroll-view>
      </view>
    </uv-popup>
    <!-- 选择下单方式弹窗（底部弹出） -->
    <uv-popup ref="orderTypePopup" mode="bottom" :round="16" :closeable="true" :overlay="true" :safeAreaInsetBottom="true" :zIndex="10000">
      <view class="order-type-popup">
        <view class="order-type-header">
          <text class="order-type-title">选择下单方式</text>
        </view>
        <view class="order-type-body">
          <view class="order-type-card" :class="{ active: selectedOrderType === 'balance' }"
            @click="selectOrderType('balance')">
            <view class="order-type-card-inner">
              <uv-icon name="red-packet" :color="'#FF6B35'" :size="60" />
              <text class="order-type-text">余额下单</text>
            </view>
          </view>
          <view class="order-type-card" :class="{ active: selectedOrderType === 'remaining ' }"
            @click="selectOrderType('remaining ')">
            <view class="order-type-card-inner">
              <uv-icon name="coupon-fill" :color="'#FF6B35'" :size="60" />
              <text class="order-type-text">余量下单</text>
            </view>
          </view>
        </view>
        <view class="order-type-footer">
          <uv-button text="完成" customStyle="border-radius: 24rpx; height: 88rpx;background-color: #FF6B35;color: #fff;"
            @click="confirmOrderType" />
        </view>
      </view>
    </uv-popup>
    <!-- 实名认证弹窗组件 -->
    <Realname ref="realnameRef" />
    <view class="tabbar-container">
      <UserTabBar />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import UserTabBar from '@/components/tabbar/UserTabBar.vue'
import Realname from '@/components/realname.vue'
import { UserInfoManager } from '@/utils/userInfo'
import { GAODE_MAP_AK } from '@/utils/config'
import { useRequest } from '@/api'
const { HOME_GOODS_LIST, SUBMIT_ORDER, GET_NOTICE_LIST, GET_PHONE_LIST ,API_SUPPLIER_NAME} = useRequest()
import moment from 'moment'
const userInfo = UserInfoManager.getUserInfo()
// 地图中心点坐标
const latitude = ref(39.908823)
const longitude = ref(116.39747)
const notice = ref('')
const oilQuantity = ref('')
const oilTime = ref('')
const oilPhone = ref('')
const oilProduct = ref('')
const nowTime = ref(Number(new Date()))
const datetimePicker = ref()
const oilProductPopup = ref()

// 油品列表数据
const oilProductList = ref([])

const chooseOilTime = () => {
  datetimePicker.value.open()
}
const confirm1 = (e: any) => {
  oilTime.value = moment(e.value).format('YYYY-MM-DD HH:mm:ss')
}
// 当前位置地址信息
const currentAddress = ref('正在获取位置...')
const currentDistrict = ref('')

// 地图标记点
const markers = ref([
  {
    id: 1,
    latitude: 39.908823,
    longitude: 116.39747,
    title: '当前位置',
    iconPath: '/static/images/start.png',
    width: 20,
    height: 30
  }
])

// 地图路线
const polyline = ref([
  {
    points: [
      { latitude: 39.908823, longitude: 116.39747 },
      { latitude: 39.908823, longitude: 116.39747 }
    ],
    color: '#FF0000DD',
    width: 2,
    dottedLine: true
  }
])

// 获取当前位置
const getCurrentLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      latitude.value = res.latitude
      longitude.value = res.longitude

      // 更新标记点
      markers.value = [
        {
          id: 1,
          latitude: res.latitude,
          longitude: res.longitude,
          title: '当前位置',
          iconPath: '/static/images/start.png',
          width: 20,
          height: 30
        }
      ]

      // 更新路线
      polyline.value = [
        {
          points: [
            { latitude: res.latitude, longitude: res.longitude },
            { latitude: res.latitude, longitude: res.longitude }
          ],
          color: '#FF0000DD',
          width: 2,
          dottedLine: true
        }
      ]

      // 获取详细地址信息
      getAddressFromLocation(res.latitude, res.longitude)

      uni.showToast({
        title: '位置获取成功',
        icon: 'success'
      })
    },
    fail: (err) => {
      currentAddress.value = '获取位置失败'
      currentDistrict.value = ''
      uni.showToast({
        title: '位置获取失败',
        icon: 'none'
      })
    }
  })
}

// 根据坐标获取详细地址
const getAddressFromLocation = (lat: number, lng: number) => {
  uni.request({
    url: 'https://restapi.amap.com/v3/geocode/regeo',
    data: {
      key: GAODE_MAP_AK,
      location: `${lng},${lat}`,
      output: 'json',
      extensions: 'base'
    },
    success: (res: any) => {
      if (res.data.status === '1') {
        const result = res.data.regeocode
        const addressComponent = res.data.regeocode.addressComponent

        currentAddress.value = result.formatted_address || '未知地址'
        currentDistrict.value = `${addressComponent.province}${addressComponent.city}${addressComponent.district}`
      } else {
        currentAddress.value = '地址解析失败'
        currentDistrict.value = ''
      }
    },
    fail: (err) => {
      currentAddress.value = '获取地址失败'
      currentDistrict.value = ''
    }
  })
}
const current = ref(1)
const pageSize = ref(5)
const allTotal = ref(0)
const loadingMore = ref(false)
const noMore = ref(false)
const getGoods = async () => {
  const params = {
    isdriver: UserInfoManager.lastrole(),
    page: current.value,
    page_size: pageSize.value
  }
  const res = await HOME_GOODS_LIST(params)
  if (res.code === 1) {
    const list = res.data.data || []
    if (current.value === 1) {
      oilProductList.value = list
    } else {
      oilProductList.value = oilProductList.value.concat(list)
    }
    allTotal.value = res.data.total || 0
    if (oilProductList.value.length) {
      oilProductList.value.forEach((item) => {
        item.type = item.goods_name.substring(0, 2)
      })
    }
    noMore.value = oilProductList.value.length >= allTotal.value
  }
}
const loadMore = async () => {
  if (loadingMore.value || noMore.value) return
  loadingMore.value = true
  current.value += 1
  await getGoods()
  loadingMore.value = false
}
// 页面加载时获取位置


const onRegionChange = (e: any) => { }

function chooseAddress() {
  uni.navigateTo({
    url: '/user/home/chooseAddress'
  })
}
function chooseOilProduct() {
  oilProductPopup.value.open()
}

function closeOilProductPopup() {
  oilProductPopup.value.close()
}
const oilProductId = ref('')
function orderOilProduct(item: any) {
  oilProduct.value = item.goods_name
  oilProductId.value = item.id
  oilProductPopup.value.close()
}
const submitOrder = () => {
  if (!oilProduct.value) {
    uni.showToast({
      title: '请选择油品',
      icon: 'none'
    })
    return
  }
  if (!oilQuantity.value) {
    uni.showToast({
      title: '请输入用油量',
      icon: 'none'
    })
    return
  }
  if (!oilTime.value) {
    uni.showToast({
      title: '请选择用油时间',
      icon: 'none'
    })
    return
  }
  if (!oilPhone.value) {
    uni.showToast({
      title: '请输入联系方式',
      icon: 'none'
    })
    return
  }

  orderTypePopup.value && orderTypePopup.value.open()
}

const realnameRef = ref()
// 选择下单方式弹窗逻辑
const orderTypePopup = ref()
const selectedOrderType = ref<'balance' | 'remaining '>('balance')
const selectOrderType = (type: 'balance' | 'remaining ') => {
  selectedOrderType.value = type
}
const confirmOrderType = async () => {
  if(selectedOrderType.value === 'balance'){
    if(userInfo.balance < 1000){
      uni.showToast({
        title: '余额不足',
        icon: 'none'
      })
      return
    }
  }
 
  const params = {
    goods_id: oilProductId.value,
    usage: oilQuantity.value,
    use_time: oilTime.value,
    address_mobile: oilPhone.value,
    lat: latitude.value,
    lng: longitude.value,
    order_type: selectedOrderType.value,
    address_detail: currentAddress.value,
    isdriver: UserInfoManager.lastrole(),
  }
  const res = await SUBMIT_ORDER(params)
  if (res.code === 1) {
    uni.showToast({
      title: '下单成功',
      icon: 'success'
    })
    orderTypePopup.value && orderTypePopup.value.close()
    uni.reLaunch({
      url:'/user/order/index'
    })
  }
}
const infoTitle = ref({
  carrier:'',
  supplier:''
})
const getNameList =async()=>{
  const res = await API_SUPPLIER_NAME()
  if(res.code ===1){
    infoTitle.value = res.data
  }
}
onMounted(() => {
  getNameList()
  getNotice()
  getGoods()
  getPhone()
  getCurrentLocation()
  // 进入页面立即弹出实名认证弹窗
  setTimeout(() => {
    if (!userInfo.isrealname) {
      realnameRef.value && realnameRef.value.open()
    }
  }, 0)
  uni.$on('refList', (item) => {
    currentAddress.value = item.address_detail
    oilPhone.value = item.address_mobile
    latitude.value = item.lat
    longitude.value = item.lng
    currentDistrict.value = item.province + item.city + item.region
  })
})
const getNotice = async () => {
  const res = await GET_NOTICE_LIST()
  if (res.code === 1) {
    notice.value = res.data.notice || ''
  }
}
const getPhone = async () => {
  const res = await GET_PHONE_LIST()
  if (res.code === 1) {
    kfPhone.value = res.data.customer
  }
}
const kfPhone = ref('')
const callPhone = () => {
  if (!kfPhone.value) {
    uni.showToast({ title: '暂无客服电话', icon: 'none' })
    return
  }
  uni.makePhoneCall({ phoneNumber: kfPhone.value })
}
// 地图内置客服电话按钮（原生控件层，盖在地图上）
// 注意：高德/微信等 map 控件仅支持 left/top 定位，不支持 right/bottom
const controlSize = 33
const controlMargin = 20
const sysInfo = uni.getSystemInfoSync()
const mapHeightPx = uni.upx2px(500) // 与 map 高度保持一致（500rpx）
const mapControls = computed(() => {
  const position = {
    left: sysInfo.windowWidth - controlMargin - controlSize,
    top: mapHeightPx - controlMargin - controlSize,
    width: controlSize,
    height: controlSize
  }
  return [
    {
      id: 1001,
      position,
      clickable: true,
      iconPath: '/static/images/phone.png'
    }
  ]
})
const onControlTap = (e: any) => {
  const id = (e && (e.detail?.controlId ?? e.detail?.controlid)) ?? e?.controlId ?? e?.controlid
  if (id === 1001) {
    callPhone()
  }
}
onUnmounted(() => {
  uni.$off('refList')
})
</script>

<style lang="scss" scoped>
.content-area {
  position: relative;
}

.notice-bar-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
}

.phone-container {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;

  z-index: 999;
}

.card-wrap {
  padding: 16rpx;
}

.addr-title-box {
  display: flex;
  flex-direction: column;
}

.addr-title {

  font-weight: 700;
  color: #222;
  line-height: 44rpx;
}

.addr-detail {
  margin-top: 6rpx;
  font-size: 26rpx;
  color: #9aa0a6;
  line-height: 36rpx;
}

.tabbar-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

/* 油品选择弹窗样式 */
.oil-product-popup {
  width: 100%;
  background: #fff;
  border-radius: 16rpx 16rpx 0 0;
  overflow: hidden;
}

.popup-header {
  padding: 40rpx 0 20rpx;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.popup-content {
  padding: 0 36rpx 24rpx;
  max-height: 60vh;
  overflow-y: auto;
  box-sizing: border-box;
}

.oil-product-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f8f8f8;

  &:last-child {
    border-bottom: none;
  }
}

.oil-type-badge {
  width: 80rpx;
  height: 80rpx;
  background: #fff3ed;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.oil-type-text {
  font-size: 24rpx;
  font-weight: 600;
  margin-top: 4rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-right: 24rpx;
}

.product-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  line-height: 44rpx;
  margin-bottom: 8rpx;
}

.price-info {
  display: flex;
  align-items: baseline;
}

.currency {
  font-size: 24rpx;
  color: #FF6B35;
  font-weight: 500;
}

.price {
  font-size: 36rpx;
  color: #FF6B35;
  font-weight: 600;
  margin: 0 4rpx;
}

.unit {
  font-size: 24rpx;
  color: #999;
}

.list-footer {
  width: 100%;
  text-align: center;
  color: #999;
  font-size: 22rpx;
}

/* 选择下单方式弹窗样式 */
.order-type-popup {
  width: 100%;
  background: linear-gradient(to bottom, #fff6e8, #fff);
  border-radius: 16rpx 16rpx 0 0;
  overflow: hidden;
  box-sizing: border-box;
}

.order-type-header {
  padding: 32rpx 24rpx 16rpx;
  text-align: center;
}

.order-type-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.order-type-body {
  display: flex;
  gap: 20rpx;
  padding: 0 36rpx 16rpx; /* 加大左右内边距，避免右侧留白视觉不齐与贴边 */
  margin-top: 16rpx;
  box-sizing: border-box;
}

.order-type-card {
  flex: 1;
  background: #fff;
  border-radius: 16rpx;
  border: 2rpx solid #eee;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.06);
}

.order-type-card-inner {
  height: 220rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.order-type-text {
  margin-top: 12rpx;
  font-size: 28rpx;
  color: #333;
}

.order-type-card.active {
  border-color: #FF6B35;
  box-shadow: 0 8rpx 24rpx rgba(255, 107, 53, 0.2);
}

.order-type-footer {
  padding: 24rpx;
}
</style>
